from datetime import datetime, timedelta

from django.contrib.auth.models import Permission, Group
from django.db.models import Q
from rest_framework import serializers, permissions, generics, filters, viewsets
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.views import JSONWebTokenAPIView

from apps.goods.models import SKU, SKUImage
from apps.meiduo_admin.serializers import MyJSONWebTokenSerializer, UserSerializer, PermissionSerializer, \
    GroupSerializer, AdminSerializer, SKUSerializer, ImageSerializer
from apps.meiduo_admin.utils import get_month_date_range
from apps.users.models import User


class MyObtainJSONWebToken(JSONWebTokenAPIView):
    serializer_class = MyJSONWebTokenSerializer


# 日活用户数量统计的类视图
class UserDailyActiveCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request):
        # 1. 得到当天的日期 (00:00:00)
        now_date = datetime.today().date()
        # 2. 查出登录的时间大于等于当天日期的用户的数量
        count = User.objects.filter(last_login__gte=now_date).count()

        return Response({
            "date": now_date,
            "count": count
        })

# 获取当天有下单的用户数量的类视图
class UserDailyOrderCountView(APIView):
    def get(self, request):
        # 1. 获取今天的日期
        date = datetime.today().date()
        # 查出当天有下单的用户的数量
        count = User.objects.filter(orderinfo__create_time__gte=date).distinct().count()
        # 返回日活结果
        return Response({"count":count, "date": date})

# 每日新用户数折线的类视图
class UserMonthCountView(APIView):
    def get(self, request):
        # 1. 得到当天的日期
        today = datetime.today().date()
        # 2. 得到日期对应月份的第一天和最后一天的日期
        date_range = get_month_date_range(today)
        # 3. 迭代查询每天新增的用户数
        resplist = []

        for date in date_range:
            tomorrow = date + timedelta(days=1)
            count = User.objects.filter(
                date_joined__gte=date, date_joined__lt=tomorrow
            ).count()
            resplist.append({
                "date": date.strftime('%Y-%m-%d'),
                'count': count
            })

        return Response(resplist)

class UserListView(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'mobile']

    # def get_queryset(self):
    #     queryset = super(UserListView, self).get_queryset()
    #     keyword = self.request.query_params.get('keyword')
    #     if keyword:
    #         queryset = queryset.filter(Q(username__contains=keyword)|Q(mobile__contains=keyword))
    #     return queryset

# 权限的视图集
class PermissionView(viewsets.ModelViewSet):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer

# 展示所有权限的视图
class PermissionSimpleView(generics.ListCreateAPIView):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    pagination_class = None


# 权限组的视图集
class GroupView(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


# 管理员的类视图
class GroupSimpleView(generics.ListAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    pagination_class = None

# 10. 管理员的视图集
class AdminView(viewsets.ModelViewSet):
    queryset = User.objects.filter(is_staff=True)
    serializer_class = AdminSerializer


class SKUSimpleView(generics.ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer
    pagination_class = None


# 12. SKU图片的视图集
class ImageView(viewsets.ModelViewSet):
    queryset = SKUImage.objects.all().order_by('-create_time')
    serializer_class = ImageSerializer